package org.example.tree;

import java.util.*;

public class TreeUtils {

    public static <T> List<TreeNode<T>> treeList(List<T> list, TreeFunction<T> treeFunction) {
        // map 提取 key 父节点id ; value 父节点下的子节点
        Map<String, List<TreeNode<T>>> map = new HashMap<>();
        // 使用uuid 做为临时父节点。避免数据不规范问题
        String rootKey = UUID.randomUUID().toString();
        for (T t : list) {
            String pid;
            if (treeFunction.isRoot(t)) {
                pid = rootKey;
            } else {
                pid = treeFunction.getPid(t);
            }
            // 此时只有单层级，没有多层级
            if (map.containsKey(pid)) {
                List<TreeNode<T>> treeNodes = map.get(pid);
                treeNodes.add(new TreeNode<>(t));
                // level 等级为1
            } else {
                List<TreeNode<T>> treeNodes = new ArrayList<>();
                treeNodes.add(new TreeNode<>(t));
                map.put(pid, treeNodes);
            }
        }
        // 对节点内部child赋值,节点id = map.key
        for (Map.Entry<String, List<TreeNode<T>>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<TreeNode<T>> treeNodes = entry.getValue();
            for (TreeNode<T> treeNode : treeNodes) {
                String id = treeFunction.getid(treeNode.getData());
                List<TreeNode<T>> childTreeNode = map.get(id);
                treeNode.setChildren(childTreeNode);
            }
        }
        return map.get(rootKey);
    }


}
